package com.nwpu.server.learning.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.nwpu.server.common.constant.CacheConstants;
import com.nwpu.server.common.response.PageUtils;
import com.nwpu.server.common.response.Query;
import com.nwpu.server.learning.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.nwpu.server.learning.dao.NetworkDao;
import com.nwpu.server.learning.entity.NetworkEntity;
import com.nwpu.server.learning.service.NetworkService;


@Service("networkService")
public class NetworkServiceImpl extends ServiceImpl<NetworkDao, NetworkEntity> implements NetworkService {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<NetworkEntity> page = this.page(
                new Query<NetworkEntity>().getPage(params),
                new QueryWrapper<NetworkEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<NetworkEntity> listTree() {
        // 旭日图是死数据因而存储时间设置为固定值
        if (!RedisUtils.hasKey(CacheConstants.NETWORK_GRAPH)) {
            // 从数据库中查询
            List<NetworkEntity> ans = getNetworkTree(-1);
            String ansJson = JSONUtil.toJsonStr(ans);
            // 设置更新时间10分钟
            RedisUtils.set(CacheConstants.NETWORK_GRAPH, ansJson, 10, TimeUnit.MINUTES);
            return ans;
        } else {
            // 已经查询到缓存直接返回
            return JSON.parseObject((String) RedisUtils.get(CacheConstants.NETWORK_GRAPH), new TypeReference<List<NetworkEntity>>() {});
        }
    }

    private List<NetworkEntity> getNetworkTree(int root) {
        return baseMapper.getNetworkTree(root);
    }

}